package com.kgc.scd.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kgc.scd.annotation.RequestPermission;
import com.kgc.scd.bean.Cart;
import com.kgc.scd.bean.OrderItemResult;
import com.kgc.scd.contant.CommonConstant;
import com.kgc.scd.mapper.CartMapper;
import com.kgc.scd.service.SubmitOrderService;
import com.kgc.scd.util.MyUtils;
import com.kgc.scd.util.RequestResult;
import com.kgc.scd.util.ResultBuildUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created On : 2022/6/14.
 * <p>
 * Author     : 98730
 * <p>
 * Description: 下单操作入口
 */
@Slf4j
@RestController
public class SubmitOrderController {

    @Autowired(required = false)
    private SubmitOrderService submitOrderService;
    @Autowired(required = false)
    private CartMapper cartMapper;

    /**
     * @author : 98730
     * @date   : 2022/6/14
     * @param  : []
     * @return : java.lang.String
     * @description : 生成订单号
     */
    public String generateOrderId(){
        // 生成用户ID的组成规则：系统标识+时间字符串+随机序列号
        return "O"
                + LocalDateTime.now().format(DateTimeFormatter.ofPattern(CommonConstant.TIME_PATTERN_MINUTE))
                + MyUtils.generateNonceStrUseUUID(4);
    }

    /**
     * @author : 98730
     * @date   : 2022/6/14
     * @param  : [java.util.List<java.lang.Integer>]
     * @return : java.util.List<com.kgc.scd.bean.OrderItemResult>
     * @description : 添加订单/订单项，返回订单集合
     */
    @PostMapping("/orderItemResultList")
    public RequestResult<Map<String,String>>  orderItemResultList(@RequestParam List<Integer> cartIds){

        String orderId = generateOrderId();
        HashMap<String, String> result = new HashMap<>();

        log.info("---------------"+orderId);
        log.info("cartIds:{},orderId:{}",cartIds,orderId);
        submitOrderService.addOrderItem(cartIds, orderId);

        submitOrderService.addOrder(cartIds,orderId);
        // 去购物车中删除
        Integer delid = cartIds.get(0);

        QueryWrapper<Cart> cartQueryWrapper = new QueryWrapper<>();
        cartQueryWrapper.in("cart_id",cartIds);
        cartMapper.delete(cartQueryWrapper);
        result.put("cartId",delid.toString());
        result.put("orderId",orderId);
        return ResultBuildUtil.success(result);

    }

}
